﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Util;
using Coldairarrow.Util.Utilities;
using EFCore.Sharding;
using LinqKit;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;


namespace Coldairarrow.Business.Base_Manage
{
    public class Base_ApiBusiness : BaseBusiness<Base_Api>, IBase_ApiBusiness, ITransientDependency
    {
        public Base_ApiBusiness(IDbAccessor db)
            : base(db)
        {
        }

        #region 外部接口

        private WebResponseContent Response { get; set; }
        public async Task<PageResult<Base_Api>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_Api>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_Api, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Base_Api> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(Base_Api data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(Base_Api data)
        {
            var model = GetEntity(data.Id);
            model.Remark = data.Remark;
            model.Url = data.Url;
            model.ItemName = data.ItemName;
            await UpdateAsync(model);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<string> ExPortToExcel(PageInput<ConditionDTO> input)
        {
            var q = await GetDataListAsync(input);
            List<Base_Api> list = q.Data;
            string tableName = Db.GetIQueryable<Sys_TableInfo>().Where(x=>x.TableName=="Base_Api").FirstOrDefault()?.CnName;
            string fileName = tableName + DateTime.Now.ToString("yyyyMMddHHssmm") + ".xlsx";
            string folder = DateTime.Now.ToString("yyyyMMdd");
            string template = $"Download/ExcelExport/{folder}/";
            string savePath = Path.Combine("wwwroot", template);         
            List<string> exportColumn = Db.GetIQueryable<Sys_TableColumn>().Where(x => x.TableName=="Base_Api"&&x.IsDisplay==1&&x.Table_Id > 0).Select(e=>e.ColumnName).ToList();
            //ExportColumns 增加扩展指定导出模板的列
            EPPlusHelper.Export(list, exportColumn, null, savePath, fileName);
            //2022.01.08优化导出功能
            return (template + fileName);
        }

        /// <summary>
        /// 2021.07.04增加code="-1"强制返回
        /// </summary>
        /// <returns></returns>
        private bool CheckResponseResult()
        {
            return !Response.Status || Response.Code == "-1";
        }


        public WebResponseContent ImportToExcel(List<IFormFile> files)
        {
            if (files == null || files.Count == 0)
                return new WebResponseContent { Status = true, Message = "请选择上传的文件" };
            IFormFile formFile = files[0];
            string savePath = $"Upload/{DateTime.Now.ToString("yyyMMdd")}/{typeof(Base_Api).Name}/";
            string dicPath = Path.Combine("wwwroot", savePath);
            if (!Directory.Exists(dicPath)) Directory.CreateDirectory(dicPath);
            dicPath = $"{dicPath}{Guid.NewGuid().ToString()}_{formFile.FileName}";

            using (var stream = new FileStream(dicPath, FileMode.Create))
            {
                formFile.CopyTo(stream);
            }
            try
            {
                //2022.06.20增加原生excel读取方法(导入时可以自定义读取excel内容)
                Response = EPPlusHelper.ReadToDataTable<Base_Api>(dicPath, null, null, null);
            }
            catch (Exception ex)
            {
                Response.Error("未能处理导入的文件,请检查导入的文件是否正确");
            }
            if (CheckResponseResult()) return Response;
            List<Base_Api> list = Response.Data as List<Base_Api>;
            List<Base_Api> newlist = new List<Base_Api>();
            foreach (var model in list)
            {
                model.Id = IdHelper.GetId();
                model.CreateTime = DateTime.Now;
                model.Deleted = false;
                newlist.Add(model);
            }
            Db.InsertAsync(newlist);
            //if (ImportOnExecuting != null)
            //{
            //    Response = ImportOnExecuting.Invoke(list);
            //    if (CheckResponseResult()) return Response;
            //}
            //2022.01.08增加明细表导入判断
            //if (HttpContext.Current.Request.Query.ContainsKey("table"))
            //{
            //    ImportOnExecuted?.Invoke(list);
            //    return Response.OK("文件上传成功", list.Serialize());
            //}
            //repository.AddRange(list, true);
            //if (ImportOnExecuted != null)
            //{
            //    Response = ImportOnExecuted.Invoke(list);
            //    if (CheckResponseResult()) return Response;
            //}
            return Response.OK("文件上传成功");
        }
        #endregion
  
        #region 私有成员

        #endregion
    }
}